import { NextResponse } from 'next/server';
import { getUserIdFromAuthHeader } from '@/lib/auth';
import { createWish, getUserWishes, WishType } from '@/lib/wishes';

export async function GET(request: Request) {
  try {
    const userId = getUserIdFromAuthHeader(request);
    if (!userId) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    const { searchParams } = new URL(request.url);
    const typeParam = searchParams.get('type') as WishType | null;
    const q = searchParams.get('q') || undefined;
    const data = await getUserWishes(userId, { type: typeParam || undefined, q });
    return NextResponse.json({ data });
  } catch (error) {
    console.error('获取愿望列表错误:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const userId = getUserIdFromAuthHeader(request);
    if (!userId) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    const { content, type } = await request.json();
    if (!content || !type || (type !== 'achieved' && type !== 'desired')) {
      return NextResponse.json({ error: '参数无效' }, { status: 400 });
    }
    const record = await createWish(userId, content, type);
    return NextResponse.json({ message: '创建成功', record });
  } catch (error) {
    console.error('创建愿望错误:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
}